#!/bin/sh

tmp=".$2~"

function build_and_sign() {
	apktool b "$1" -o "$tmp"
	if [ ! -f "$tmp" ];then
        	echo "apktool build failed"
                exit 1
       	fi
       	jarsigner -verbose -keystore "$2" -storepass "$3" -signedjar "$4" "$tmp" "$5"
        rm "$tmp"
}

function print_help(){
        echo "bsapk <unpacked dir> <apk-signed file> <keystore> <alias>"
        echo "bsapk --debug <unpacked dir> <apk-signed file>"
        echo "bsapk --newkey <unpacked dir> <apk-signed file> <keystore> <alias>"
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	print_help
elif [ "$1" = "--debug" ]; then
	if [ -n "$2" ] && [ -n "$3" ]; then
		build_and_sign "$2" ~/.android/debug.keystore android "$3" androiddebugkey
	else
		print_help
	fi
elif [ "$1" = "--newkey" ]; then
	if [ -n "$2" ] && [ -n "$3" ] && [ -n "$4" ] && [ -n "$5" ]; then

		if [ -f "$4" ]; then
			rm $4
		fi

		echo "Store Password:\c":
		stty -echo
		read storepass
		stty echo

		echo ""

		echo "Alias Password:\c"
		stty -echo
		read keypass
		stty echo

		keytool -genkey -alias $5 -keyalg RSA -validity 36500 -keystore $4 -keypass ${keypass} -storepass ${storepass}
		
                build_and_sign "$2" "$4" "${keypass}" "${storepass}" "$3" "$5"
	else
		print_help
	fi
elif [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] && [ -n "$4" ]; then
	if [ -d "$1" ]; then
		if [ -f "$3" ]; then
			build_and_sign "$1" "$3" "$2" "$4" "$5" "$6"
		else
			echo "Sign key does not exist."
		fi
	else
		echo "Source dir does not exist."
	fi
else
	print_help
fi
